
package com.epam.android.training.day6.task2;

import com.epam.android.training.day6.task2.Contacts.Names;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Activity responsible for adding new contacts into database.
 * 
 * @author Anton Novikov
 */
public class ContactAdder extends Activity {
  private static final String TAG = ContactAdder.class.getSimpleName();

  /** Called when the activity is starting. */
  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contact_adder);
    final Intent intent = getIntent();

    if (intent != null && Intent.ACTION_INSERT.equals(intent.getAction())) {
      addSaveButtonAction();

      addCancelButtonAction();
    } else {
      // unknown action
      Log.e(TAG, "Unknown action, exiting");
      finish();
      return;
    }
  }

  /**
   * Adds save button action. Finishes activity after data is saved into
   * database.
   */
  private void addSaveButtonAction() {
    Button create = (Button) findViewById(R.id.create_button);
    create.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        EditText firstNameView = (EditText) findViewById(R.id.first_name);
        EditText lastNameView = (EditText) findViewById(R.id.last_name);

        ContentValues values = new ContentValues();
        values.put(Names.FIRST_NAME, firstNameView.getText().toString());
        values.put(Names.LAST_NAME, lastNameView.getText().toString());
        getContentResolver().insert(Names.CONTENT_URI, values);
        Toast.makeText(ContactAdder.this, R.string.success_message, Toast.LENGTH_SHORT).show();
        finish();
      }
    });
  }

  /**
   * Adds cancel button action. Finishes activity without saving data on the
   * form.
   */
  private void addCancelButtonAction() {
    Button cancel = (Button) findViewById(R.id.cancel_button);
    cancel.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        finish();
      }
    });
  }
}
